package com.gl.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FormController {

	@RequestMapping(value = "upload_enter", method = RequestMethod.GET)
	public String enter(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		// 进入下载界面
		return "upload";
	}

	/**
	 * 具体的实现下载功能
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public void upload(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 得到上传的文件
		MultipartFile mFile = multipartRequest.getFile("file");
		
		MultipartFile mFile11 = multipartRequest.getFile("file11");
		
		String name = (String)(multipartRequest.getAttribute("name"));
		String userName = request.getParameter("name");
		String userName1 = multipartRequest.getParameter("name");
		// 得到上传服务器的路径
	//	String path = request.getSession().getServletContext()
//				.getRealPath("/WEB-INF/upload/");
		// 得到上传的文件的文件名
		String filename = mFile.getOriginalFilename();
		String filename11 = mFile11.getOriginalFilename();
	//	InputStream inputStream = mFile.getInputStream();
	//	byte[] b = new byte[1048576];
		//int length = inputStream.read(b);
		String path = "C:\\" + filename;
		// 文件流写到服务器端
//		FileOutputStream outputStream = new FileOutputStream(path);
//		outputStream.write(b, 0, length);
//		inputStream.close();
//		outputStream.close();
		
		File file = new File(path);
		byte[] bytes = mFile.getBytes();
		FileOutputStream fos = new FileOutputStream(file, false);	// 覆盖
		fos.write(bytes);
		fos.close();
	}
	
	
	@RequestMapping(value = "addfile")
	public String upload(HttpServletRequest request,
			@RequestParam("file") MultipartFile fileUpload)	throws Exception {
		if (!fileUpload.isEmpty()) {
			String dirPath = "D:/myimg";
			File dirFile = new File(dirPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			File uploadFile = new File(dirFile,
					fileUpload.getOriginalFilename());
			InputStream is = fileUpload.getInputStream();
			FileOutputStream fos = new FileOutputStream(uploadFile);
			byte[] tmp = new byte[1024];
			int len = -1;
			while ((len = is.read(tmp)) != -1) {
				fos.write(tmp, 0, len);
			}
			is.close();
			fos.flush();
			fos.close();
			System.out.println("文件上传从成功：" + uploadFile.getParent());
		}
		return "/jsp/fileUpload/upload.jsp";
	}
	
	 
	/**
	 * 文件下载
	 * @createTime:2012-6-19
	 * @param fileName
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/download/{fileName}")
	public ModelAndView download(@PathVariable("fileName") String fileName,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null; // 从文件中读取内容
		BufferedOutputStream bos = null; // 向文件中写入内容
		// 获得服务器上存放下载资源的地址
		String ctxPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\" + "fileupload\\";
		// 获得下载文件全路径
		String downLoadPath = ctxPath + fileName;
		System.out.println(downLoadPath);
		// 如果文件不存在,退出
		File file = new File(downLoadPath);
		if (!file.exists()) {
			return null;
		}
		try {
			// 获得文件大小
			long fileLength = new File(downLoadPath).length();
			System.out.println(new String(fileName.getBytes("utf-8"),
					"ISO-8859-1"));
			response.setContentType("text/html;charset=utf-8"); // 设置相应类型和编码
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));

			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			// 定义文件读取缓冲区
			byte[] buff = new byte[2048];
			int bytesRead;
			// 把下载资源写入到输出流
			while ((bytesRead = bis.read(buff, 0, buff.length)) != -1) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}
}
